package cn.muqingfeng.api.request;

import java.io.UnsupportedEncodingException;
import java.util.Map;

import android.net.Uri;
import android.net.Uri.Builder;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

public class GsonRequest<T> extends BaseGsonRequest<T> {
	private Class<T> mClazz;
	private Listener<T> mResListener;
	private Map<String, String> mParams;

	public GsonRequest(int method, String url, Listener<T> responseListener, ErrorListener errorListener, Map<String, String> params, Class<T> clazz) {
		super(method, url, errorListener);
		this.mClazz = clazz;
		mResListener = responseListener;
		this.mParams = params;
	}

	@Override
	protected Response<T> parseNetworkResponse(NetworkResponse response) {
		String responseStr;
		try {
			responseStr = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
		} catch (UnsupportedEncodingException e) {
			responseStr = new String(response.data);
		}
		try {
			Gson gson = createGson();
			T result = gson.fromJson(responseStr, mClazz);
			return Response.success(result, HttpHeaderParser.parseCacheHeaders(response));
		} catch (JsonSyntaxException e) {
			e.printStackTrace();
			return Response.error(new ParseError(e));
		}
	}

	@Override
	protected void deliverResponse(T response) {
		if (mResListener != null) {
			mResListener.onResponse(response);
		}
	}

	@Override
	public Map<String, String> getHeaders() throws AuthFailureError {
		return mApiContext.getHeaders(mNeedLogin);
	}

	@Override
	protected Map<String, String> getParams() throws AuthFailureError {
		return mParams;
	}

	@Override
	public String getUrl() {
		if (getMethod() == Method.GET && mParams != null && !mParams.isEmpty()) {
			Builder builder = Uri.parse(super.getUrl()).buildUpon();
			for (String key : mParams.keySet()) {
				builder.appendQueryParameter(key, mParams.get(key));
			}
			return builder.toString();
		}
		return super.getUrl();
	}

	@Override
	public String getCacheKey() {
		if (getMethod() == Method.POST && mParams != null && !mParams.isEmpty()) {
			Builder builder = Uri.parse(super.getUrl()).buildUpon();
			for (String key : mParams.keySet()) {
				builder.appendQueryParameter(key, mParams.get(key));
			}
			return builder.toString();
		}
		return getUrl();
	}

}
